$(document).ready(function () {

    initSubMenu();
    queryTableList(1);
    queryDevice()

    layui.use(function () {

        var layer = layui.layer;

        // 表格
        form = layui.form;
        form.on('select(eventType)', function (data) {//状态下拉
            $('div[lay-filter="search"]').click();
        });
        form.on('select(loopType)', function (data) {//节点类型下拉
            $('div[lay-filter="search"]').click();
        });
        form.on('select(searchCode)', function (data) {//按设备查询
            $('div[lay-filter="search"]').click();
        });

        form.on('select(eventTypeRecord)', function (data) {//历史记录节点状态下拉
            $('div[lay-filter="search-record"]').click();
        });
        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            params.nodeName = params.node_name
            params.nodeNum = params.node_num

            queryTableList(1)
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        form.on('submit(search-record)', function (data) {//监听历史查询
            recordParams = data.field;
            if (recordParams.record_date != '') {
                let date = recordParams.record_date.split(' - ')
                recordParams.beginTime = date[0]
                recordParams.endTime = date[1]
            }
            queryRecordTable()
            return false;
        });

        form.on('submit(search-alarm)', function (data) {//监听告警查询
            alarmParams = data.field;
            if (alarmParams.alarm_date != '') {
                let date = alarmParams.alarm_date.split(' - ')
                alarmParams.beginTime = date[0]
                alarmParams.endTime = date[1]
            }
            queryAlarmTable()
            return false;
        });

    });
})
var params = {};//查询条件参数
var form, unit;
var drawer;//抽屉实例
var curNodeId = null;//当前选中节点
var curLoopType = null;//当前选中节点的类型


// 查询设备总数
queryDevice = () => {

    new AjaxChain()
        .setUrl('/device/list/all?type=7')
        .then(data => {
            typeStr = data.reduce((x, y) => {
                return x + `<option value="${y.code}">${y.name + '（' + y.code + '）'}</option>`
            }, '<option value="">设备名称或编号(可搜索)</option>')

            $('#search-code').empty().append(typeStr)

            form.render('select');
        })
        .send();
}

// 节点分页
queryTablePage = (total) => {

    var laypage = layui.laypage;


    laypage.render({
        elem: 'card-page',
        count: total,
        limit: 12,
        groups: 3,
        prev: '<i class="layui-icon layui-icon-left"></i>',
        next: '<i class="layui-icon layui-icon-right"></i>',
        layout: ['prev', 'page', 'next', 'count'],
        jump: function (obj, first) {

            if (!first) {

                queryTableList(obj.curr)

            }

        }

    });


}

//查询节点列表
queryTableList = (pN) => {
    params.pageNum = pN
    params.pageSize = 12;

    new AjaxChain()
        .setUrl('/data/electric/list/status')
        .setData(params)
        .then(data => {

            if (pN == 1) {
                queryTablePage(data.total)
            }

            if (data.total == 0) {
                $('.card-content').empty().append('<div class="no-data">未查询到节点</div>')
                return
            }

            $('.card-content').empty()
                .append(
                    data.data.reduce(
                        (x, y) => {
                            var status = ''
                            if (y.eventType == 701) {
                                status = 'warn'
                            } else {
                                status = 'normal'
                            }
                            return x +
                                `<div class="card-item gradient-card device-${status}" onclick='openDetail("${y.nodeId}","${y.loopType}","${y.deviceName}","${y.nodeName}",${JSON.stringify(y)})'>
                                <div class="card-item-title">
                                    ${y.deviceName}
                                    <span class="card-item-status">${y.eventTypeDesc || '暂无'}</span>
                                </div>
                                <div class="card-item-con">
                                    <div class="card-item-icon">
                                        <img src="../static/img/rd.png" alt="">
                                    </div>
                                    <div class="card-item-msg">
                                        <div>节点名称：${y.nodeName}</div>
                                        <div>节点编号：${y.nodeNum}</div>
                                        <div>节点类型：${y.loopTypeDesc}</div>
                                        <div>设备编号：${y.deviceCode}</div>
                                        <div>上报时间：${y.dataTime || ''}</div>
                                    </div>
                                </div>
                            </div>`
                        }, ''
                    ))

        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();
}


// 打开节点详情弹窗
var titLayer = null;
function openDetail(nodeId, loopType, deviceName, nodeName, res) {
    curNodeId = nodeId;
    curLoopType = loopType;

    var temperature,
        voltage,
        current

    switch (parseInt(curLoopType)) {
        case 1:
            temperature = `<div>${res.temperatureA||''}</div>`
            voltage = `<div>${res.voltageA||''}</div>`
            current = `<div>${res.currentA||''}</div>`
            break;
        case 2:
            temperature = `<div>1：${res.temperatureA||''}</div><div>2：${res.temperatureB||''}</div>`
            voltage = `<div>${res.voltageA||''}</div>`
            current = `<div>${res.currentA||''}</div>`
            break;
        case 3:
            temperature = `<div>1：${res.temperatureA||''}</div><div>2：${res.temperatureB||''}</div><div>3：${res.temperatureC||''}</div>`
            voltage = `<div>A：${res.voltageA||''}</div><div>B：${res.voltageB||''}</div><div>C：${res.voltageC||''}</div>`
            current = `<div>A：${res.currentA||''}</div><div>B：${res.currentB||''}</div><div>C：${res.currentC||''}</div>`
            break;
        case 4:
            temperature = `<div>1：${res.temperatureA||''}</div><div>2：${res.temperatureB||''}</div><div>3：${res.temperatureC||''}</div><div>4：${res.temperatureD||''}</div>`
            voltage = `<div>A：${res.voltageA||''}</div><div>B：${res.voltageB||''}</div><div>C：${res.voltageC||''}</div>`
            current = `<div>A：${res.currentA||''}</div><div>B：${res.currentB||''}</div><div>C：${res.currentC||''}</div>`
            break;

        default:
            break;
    }



    layer.tab({
        area: ['100%', '100%'],
        // maxmin: true,
        // shade: 0.9,
        move: false,
        tab: [
            {
                title: '<div  onclick=switchTab(1,"' + deviceName + '","' + nodeName + '","' + loopType + '")><img src="../static/img/tab1.png">基本信息</div>',
                content: `<div class="contain-tab tab-con">
                            <div class="tab-title">基本信息</div>
                            <div class="tab-item">
                                <div class="layui-col-md3">所属设备 ：${res.deviceName}</div>
                                <div class="layui-col-md3">设备编码 ：${res.deviceCode}</div>
                                <div class="layui-col-md3">节点名称 ：${res.nodeName}</div>
                                <div class="layui-col-md3">节点号 ：${res.nodeNum}</div>
                                <div class="layui-col-md3">节点类型 ：${res.loopTypeDesc}</div>
                                <div class="layui-col-md3">设备状态 ：${res.deviceStatusDesc || ''}</div>
                                <div class="layui-col-md3">节点状态 ：${res.eventTypeDesc || ''}</div>
                            </div>
                            <div class="tab-title">设备数据</div>
                            <div class="tab-item">
                                <div class="layui-col-md2 data-item">
                                    <div class="data-item-title">
                                        <img src="../static/img/temperature.png">温度(°C)
                                    </div>
                                    <div class="data-item-value">
                                       ${temperature}
                                    </div>
                                </div>
                                <div class="layui-col-md2 data-item">
                                    <div class="data-item-title">
                                        <img src="../static/img/residualCurrent.png">剩余电流(mA)
                                    </div>
                                    <div class="data-item-value">
                                        <div>${res.residualCurrent||''}</div>
                                    </div>
                                </div>
                                <div class="layui-col-md2 data-item">
                                    <div class="data-item-title">
                                        <img src="../static/img/voltage.png">电压(V)
                                    </div>
                                    <div class="data-item-value">
                                      ${voltage}
                                    </div>
                                </div>
                                <div class="layui-col-md2 data-item">
                                    <div class="data-item-title">
                                        <img src="../static/img/current.png">电流(A)
                                    </div>
                                    <div class="data-item-value">
                                     ${current}
                                    </div>
                                </div>
                            </div>
                            <div class="tab-title">操作</div>
                            <div class="tab-item">
                                <div class="layui-btn" onclick='opGate(6,${JSON.stringify(res)})'><img src="../static/img/fenzha.png">分闸</div>
                                <div class="layui-btn" onclick='opGate(7,${JSON.stringify(res)})'><img src="../static/img/hezha.png">合闸</div>
                            </div>
                        </div>`
            },
            {
                title: '<div  onclick=switchTab(2,"' + deviceName + '","' + nodeName + '","' + loopType + '")><img src="../static/img/tab2.png">折线图</div>',
                content: $('#tab-2').html()
            },
            {
                title: '<div onclick=switchTab(3,"' + deviceName + '","' + nodeName + '","' + loopType + '")><img src="../static/img/tab3.png">历史记录</div>',
                content: $('#tab-3').html()
            },
            {
                title: '<div  onclick=switchTab(4,"' + deviceName + '","' + nodeName + '","' + loopType + '")><img src="../static/img/tab4.png">历史告警</div>',
                content: $('#tab-4').html()
            }
        ],
        shadeClose: false,
        beforeEnd: function (layero, index, that) {
            if (titLayer) {
                layer.close(titLayer)
                titLayer = null;
            }
        }
    });
}


//切换弹窗tab事件
function switchTab(type, deviceName, nodeName, loopType) {

    setTimeout(() => {
        if (type == 1) {
            if (titLayer) {
                layer.close(titLayer)
                titLayer = null;
            }

        } else {

            if (!titLayer) {
                titLayer = layer.msg(`${deviceName} —— ${nodeName}（${loopType}P）`, {
                    offset: 'r',
                    skin: 'class-layer-titLayer',
                    time: 0
                })
            }

        }


        switch (type) {
            case 1:

                break;
            case 2:
                queryNodesChart()
                break;
            case 3:
                queryRecordTable()
                break;
            case 4:
                queryAlarmTable()
                break;

            default:
                break;
        }
    }, 300);
}



// 节点基本信息
function showNodeDetails() {

}

// 分闸合闸操作
function opGate(type, res) {

    layer.confirm('确定进行该操作吗？', { icon: 3 }, function (index1) {
        layer.close(index1)

        new AjaxChain()
            .setUrl('/device/akr/ascb/command/down')
            .setMethod('post')
            .setData(JSON.stringify(
                {
                    deviceId: res.deviceId,
                    nodeId: res.nodeId,
                    deviceCode: res.deviceCode,
                    nodeNum: res.nodeNum,
                    type: type,//6分闸 7合闸
                }
            ))
            .then(data => {
                layer.open({
                    type: 2,
                    title: false,
                    closeBtn: 0,
                    isOutAnim: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: 'switch.html?type=' + type,
                    success: function (layero, index, that) {

                        setTimeout(() => {
                            layer.msg((type == 6 ? '分闸' : "合闸") + '成功')
                            layer.close(index)
                        }, 2500);

                    }

                });
            })
            .catch(err => {
                console.error('请求异常:', err);
            })
            .send();
    });



}


// 节点近七天折线图
queryNodesChart = () => {
    var today = new Date();
    var todayFormatted = today.toISOString().split('T')[0]; // 格式化为YYYY-MM-DD

    // 获取七天前的日期
    var sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
    var sevenDaysAgoFormatted = sevenDaysAgo.toISOString().split('T')[0]; // 格式化为YYYY-MM-DD

    new AjaxChain()
        .setUrl('/data/electric/list/trend')
        .setData({
            nodeId: curNodeId,
            beginTime: sevenDaysAgoFormatted,
            endTime: todayFormatted,
        })
        .then(data => {

            var xData = data.map(item => item.dataTime)

            var yRes = []

            switch (parseInt(curLoopType)) {
                case 1:
                    yRes = {
                        temperature: [data.map(item => item.temperatureA)],
                        residualCurrent: [data.map(item => item.residualCurrent)],
                        voltage: [data.map(item => item.voltageA)],
                        current: [data.map(item => item.currentA)]
                    }
                    break;
                case 2:
                    yRes = {
                        temperature: [data.map(item => item.temperatureA), data.map(item => item.temperatureB)],
                        residualCurrent: [data.map(item => item.residualCurrent)],
                        voltage: [data.map(item => item.voltageA)],
                        current: [data.map(item => item.currentA)]
                    }
                    break;
                case 3:
                    yRes = {
                        temperature: [data.map(item => item.temperatureA), data.map(item => item.temperatureB), data.map(item => item.temperatureC)],
                        residualCurrent: [data.map(item => item.residualCurrent)],
                        voltage: [data.map(item => item.voltageA), data.map(item => item.voltageB), data.map(item => item.voltageC)],
                        current: [data.map(item => item.currentA), data.map(item => item.currentB), data.map(item => item.currentC)]
                    }
                    break;
                case 4:
                    yRes = {
                        temperature: [data.map(item => item.temperatureA), data.map(item => item.temperatureB), data.map(item => item.temperatureC), data.map(item => item.temperatureD)],
                        residualCurrent: [data.map(item => item.residualCurrent)],
                        voltage: [data.map(item => item.voltageA), data.map(item => item.voltageB), data.map(item => item.voltageC)],
                        current: [data.map(item => item.currentA), data.map(item => item.currentB), data.map(item => item.currentC)]
                    }
                    break;

                default:
                    break;
            }


            for (const key in yRes) {
                if (yRes.hasOwnProperty(key)) {
                    buildCharts(xData, key, yRes[key])

                }
            }

        })
        .send();

}

// 生成表格
buildCharts = (xData, typeId, yRes) => {


    var myChart = echarts.init(document.getElementById('chart-' + typeId));

    var option = {
        color: ['#48EDFF', '#91cc75', '#fac858', '#FF3996'],
        legend: {
            show: true,
            textStyle: {
                color: '#E2F1FF'
            }
        },
        xAxis: {
            type: 'category',
            axisLabel: {
                color: "#BDE4FF"
            },
            axisTick: {
                show: false,
            },
            axisLine: {
                lineStyle: {
                    color: '#296085',
                }
            },
            data: xData
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                color: "#BDE4FF"
            },
            splitLine: {
                lineStyle: {
                    color: '#296085',
                    type: "dashed"
                }
            }
        },
        series: [

        ]
    };
    var legendData = [];
    var prefix = $('#chart-' + typeId).data().name;


    yRes.forEach((item, i) => {
        var name = (prefix + (i + 1)).substring(0, 4)
        legendData.push(name)
        option.series.push({
            name: name,
            data: item,
            type: 'line',
            lineStyle: {
                shadowColor: 'rgba(20, 20, 20, 0.9)',
                shadowBlur: 3,
                shadowOffsetX: 3,
                shadowOffsetY: 2,
            },
        })
    });
    option.legend.data = legendData

    myChart.setOption(option);
}


// 历史记录表格
var recordParams = {}
queryRecordTable = () => {

    switch (curLoopType) {
        case "1":
            var cols = [[
                { field: 'eventTypeDesc', title: '状态', align: "center" }
                , { field: 'temperatureA', title: '温度1(°C)', align: "center" }
                , { field: 'residualCurrent', title: '剩余电流(mA)', align: "center" }
                , { field: 'voltageA', title: '电压(V)', align: "center" }
                , { field: 'currentA', title: '电流(A)', align: "center" }
                , { field: 'dataTime', title: '最新上报时间', align: "center" }
            ]]
            break;
        case "2":
            var cols = [[
                { field: 'eventTypeDesc', title: '状态', align: "center" }
                , { field: 'temperatureA', title: '温度1(°C)', align: "center" }
                , { field: 'temperatureB', title: '温度2(°C)', align: "center" }
                , { field: 'residualCurrent', title: '剩余电流(mA)', align: "center" }
                , { field: 'voltageA', title: '电压(V)', align: "center" }
                , { field: 'currentA', title: '电流(A)', align: "center" }
                , { field: 'dataTime', title: '最新上报时间', align: "center" }
            ]]
            break;
        case "3":
            var cols = [[
                { field: 'eventTypeDesc', title: '状态', align: "center", rowspan: 2 }
                , { field: 'residualCurrent', title: '剩余电流(mA)', align: "center", width: 150, rowspan: 2 }
                , { title: '温度(°C)', align: "center", colspan: 3 }
                , { title: '电压(V)', align: "center", colspan: 3 }
                , { title: '电流(A)', align: "center", colspan: 3 }
                , { field: 'dataTime', title: '最新上报时间', align: "center", width: 240, rowspan: 2 }
            ], [
                { field: 'temperatureA', title: '1', align: "center" }
                , { field: 'temperatureB', title: '2', align: "center" }
                , { field: 'temperatureC', title: '3', align: "center" }
                , { field: 'voltageA', title: 'A相', align: "center" }
                , { field: 'voltageB', title: 'B相', align: "center" }
                , { field: 'voltageC', title: 'C相', align: "center" }
                , { field: 'currentA', title: 'A相', align: "center" }
                , { field: 'currentB', title: 'B相', align: "center" }
                , { field: 'currentC', title: 'C相', align: "center" }
            ]]
            break;
        case "4":
            var cols = [[
                { field: 'eventTypeDesc', title: '状态', align: "center", rowspan: 2 }
                , { field: 'residualCurrent', title: '剩余电流(mA)', align: "center", width: 150, rowspan: 2 }
                , { title: '温度(°C)', align: "center", colspan: 4 }
                , { title: '电压(V)', align: "center", colspan: 3 }
                , { title: '电流(A)', align: "center", colspan: 3 }
                , { field: 'dataTime', title: '最新上报时间', align: "center", width: 240, rowspan: 2 }
            ], [
                { field: 'temperatureA', title: '1', align: "center" }
                , { field: 'temperatureB', title: '2', align: "center" }
                , { field: 'temperatureC', title: '3', align: "center" }
                , { field: 'temperatureD', title: '4', align: "center" }
                , { field: 'voltageA', title: 'A相', align: "center" }
                , { field: 'voltageB', title: 'B相', align: "center" }
                , { field: 'voltageC', title: 'C相', align: "center" }
                , { field: 'currentA', title: 'A相', align: "center" }
                , { field: 'currentB', title: 'B相', align: "center" }
                , { field: 'currentC', title: 'C相', align: "center" }
            ]]
            break;

        default:
            break;
    }

    recordParams.nodeId = curNodeId
    recordParams.pageSize = 10;

    layui.use('table', function () {
        var table = layui.table;
        //展示已知数据
        table.render({
            elem: '#record-table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/data/electric/list/history"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: recordParams
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: cols
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页
            }
            , done: function (res, curr, count) {
                $('.layui-table-cell').height($('.contain-table-list').height() / 20);

                layui.laydate.render({
                    elem: "#record-date",
                    range: true,
                });

                form.render();
            },

        });

    });
}


// 告警记录表格
var alarmParams = {}
queryAlarmTable = () => {

    var cols = [
        [{
            field: 'lgStatusDesc',
            title: '漏电状态',
            align: 'center',
            rowspan: 2
        },
        {
            title: '温度状态',
            align: 'center',
            colspan: parseInt(curLoopType)
        },
        {
            field: 'powerStatusDesc',
            title: '功率状态',
            align: 'center',
            rowspan: 2
        },
        {
            field: 'voltageStatusDesc',
            title: '电压状态',
            align: 'center',
            rowspan: 2
        },
        {
            field: 'currentStatusDesc',
            title: '电流状态',
            align: 'center',
            rowspan: 2
        },
        {
            field: 'rlyStatusDesc',
            title: '断路器状态',
            align: 'center',
            rowspan: 2
        },
        {
            field: 'eventDetail',
            title: '告警详情',
            align: 'center',
            rowspan: 2
        },
        {
            field: 'dataTime',
            title: '最新上报时间',
            templet: function (d) {
                return d.dataTime == undefined ? '暂无' : d.dataTime.substring(0, 19)
            },
            width: 200,
            rowspan: 2,
            align: 'center'
        }], [
            {
                field: 'temp1StatusDesc',
                title: '温度1',
                align: 'center',
            },
            {
                field: 'temp2StatusDesc',
                title: '温度2',
                align: 'center',
                hide: curLoopType == 1
            },
            {
                field: 'temp3StatusDesc',
                title: '温度3',
                align: 'center',
                hide: curLoopType == 1 || curLoopType == 2
            },
            {
                field: 'temp4StatusDesc',
                title: '温度4',
                align: 'center',
                hide: curLoopType == 1 || curLoopType == 2 || curLoopType == 3
            },
        ]
    ]

    alarmParams.nodeId = curNodeId
    alarmParams.pageSize = 10;

    layui.use('table', function () {
        var table = layui.table;
        //展示已知数据
        table.render({
            elem: '#alarm-table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/data/electric/list/alarm"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: alarmParams
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: cols
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页
            }
            , done: function (res, curr, count) {
                $('.layui-table-cell').height($('.contain-table-list').height() / 20);

                layui.laydate.render({
                    elem: "#alarm-date",
                    range: true,
                });

                form.render();
            },

        });

    });
}


